const mysql  = require('mysql');
const config = require('../crawler/config/config');
const log    = require('../util/log');
const utils  = require('../util/utils');

const _TYPES = ['INSERT','insert','UPDATE','update','DELETE','delete','SELECT','select'];
class dataSource{

    constructor() {

    }

    async getConnection(){
        return new Promise((resolve, reject) => {
            let connection = mysql.createConnection(config.DATASOURCE);
            connection.connect(async (err) => {
                if(err){
                    log.err(`Connection mysql throw error. error message:${err}!!!`);
                    throw Error(`Connection mysql failed.`);
                }else{
                    log.debug(`Connection mysql successful.`);
                    resolve(connection);
                }
            })
        })
    }

    async execute(sql,params){
        return new Promise((async (resolve, reject) => {
            //识别操作类型
            let type = sql.split(' ')[0];
            if(!_TYPES.concat(type)){
                log.err(`Invalid type - [${type}]`);
                log.err(`Sql str - [${sql}]`);
                reject();
                return;
            }
            let sqlMd5 = await utils.currentTimeMd5Seq(sql);
            log.info(`Execute Sql [${sqlMd5}]\n =>:${sql}`);
            let connection = await this.getConnection();
            await connection.query(sql,params,async (err,result) => {
                if(err){
                    log.err(`[${type} Error] - : message:${err}!!!`);
                    connection.end();
                    reject(err);
                }else{
                    log.debug(`[${type} success] - sql:[${sql}] params:[${JSON.stringify(params)}]`);
                    log.info(`Result [${sqlMd5}]\n <= :${JSON.stringify(result)}`);
                    connection.end();
                    resolve(result);
                }
            })
        }))
    }
}

module.exports = dataSource;
